(in-package :wsml2reasoner)
;;;; $Id$
(defvar *verbose* t)

(defmacro verbose (message &rest parameters)
  `(if *verbose*
      (format t (concatenate 'string ,message "~%") ,@parameters)
      (finish-output)))

(defconstant +java-null+ 
  (make-immediate-object nil :ref) "a 'null' reference Java object")

(defun jenum (&optional 
	      (enum "IRIS")
	      (enum-for-name
	       "org.wsml.reasoner.api.WSMLReasonerFactory$BuiltInReasoner")
	      (key #"toString")
	      (test #'equal))
  "Return java object for ENUM from ENUM-FOR-NAME type."
  (let* ((enum-class
	  (#"forName" 'java.lang.Class
		      enum-for-name
		      nil
		      (#"getClassLoader" (jobject-class (#"getFactory"
							 'DefaultWSMLReasonerFactory)))))
	 (enum-constants (#"getEnumConstants" enum-class)))
    (find enum enum-constants :key key :test test)))

;;; XXX somehow, we have to figure out how to enumerate available classloaders
(defun jclass-dynamic (name)
  (#"forName" 'java.lang.Class
	      name
	      nil
	      (#"getClassLoader" (jobject-class (#"getFactory"
						 'DefaultWSMLReasonerFactory)))))
  


;;; XXX register-java-exception doensn't seem to work here, although
;;; the tests in ABCL seem to run ok.
(defmacro with-registered-exception (exception condition &body body)
  `(unwind-protect
       (progn
         (register-java-exception ,exception ,condition)
         ,@body)
     (unregister-java-exception ,exception)))

(eval-when (:execute)
    (define-condition java-throwable (java.lang.Throwable))
    (register-java-exception "java.lang.Throwable" 'java-throwable)
    (define-condition java-file-not-found (java-exception))
    (register-java-exception "java.io.FileNotFoundException" 'java-file-not-found))

(defun new-java-stream (file)
  (handler-case
      (let* ((pathname (namestring (merge-pathnames file)))
	     (file-input-stream (cl-user::new 'FileInputStream pathname))
	     (input-stream-reader (cl-user::new 'InputStreamReader
						file-input-stream)))
	(verbose "Opened '~A' for read." file)
	input-stream-reader)
    ;;; XXX Fix java exception hierarchy
    (java-throwable (e)
	(error "Failed to load file '~S' because of throwable: ~A"
	       file e))
    (java-exception (e)
	(error "Failed to load file '~S' because of exception: ~A"
	       file e))))


;;; XXX
(defun jstatic-field (classname field)
  (let ((class (#"forName" 'java.lang.class classname)))))
    

;; (defun jclass-cast (class cast-to)
;;   ((let )))